package com.dayuanit.dy17.atm.service.impl;

import com.dayuanit.dy17.atm.dto.FlowDTO;
import com.dayuanit.dy17.atm.service.IRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceTmpleteImpl implements IRedisService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean saveResetPwdEmail(String email) {
        String key = "atm:email:" + email;
        redisTemplate.opsForValue().setIfAbsent(key, "", 30, TimeUnit.SECONDS);

        return false;
    }

    @Override
    public void saveTop10Flows(long userId, List<FlowDTO> flows) {
        String key = "atm:flow:" + userId;
        redisTemplate.opsForValue().set(key, flows, 10, TimeUnit.SECONDS);
    }

    @Override
    public List<FlowDTO> listTop10Flows(long userId) {
        String key = "atm:flow:" + userId;
        List<FlowDTO> flows = (List<FlowDTO>)redisTemplate.opsForValue().get(key);
        return flows == null ? Collections.emptyList() : flows;
    }

    @Override
    public void expireKey(String key) {
        redisTemplate.expire(key, 0, TimeUnit.SECONDS);
    }

    @Override
    public void save4CountRequestURI(String uri) {
        String key = "atm:url:count";
        redisTemplate.opsForHash().increment(key, uri, 1);
    }
}
